//集成appjs中方法及属性
var http = require('../../../../service/http.js');//请求类
var util = require('../../../../utils/util.js');//工具类

const app = getApp();
var rd_session ='';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //----------登录操作-----------------
    showLogin: false,//展示登录页
    isAuthorization:false,//是否授權登陸
    productId:'',//商品itemid

    productObj: '',
    timeId: '',
    isshow: false,    //是否显示遮罩层
    maskHeight: 0,//遮罩层高度
    hasAddress: false,
    animationData: '',//添加地址信息
    animationData2: '',//地址列表
    ismask: false,     //是否显示遮罩层
    animationData3: '',//选择配送方式
    addCode: false,
    agree: '',//是够允许获取微信地址
    defaultAddress: {},//默认收货地址(用于展示)
    buyerMemo: '',//用户留言
    buyerMemoLength: 0,//用户留言备注

    hasLimit: false,//是否含有限购商品，

    hasUnvalid : false,//是否有失效商品
    //------------结算商品列表-参数--------------------
    submitOrderNoPay:false,//只提交订单不支付
    cartProducts: [],//结算商品列表
    totalCount: 0,//商品总额
    orderId: '',//订单id
    sendMessage: true,//是否发送短信给收货人
    //-----------根据订单id查看状态、地址----------------
    status: 10,// 10 为初始值
    orderTime: '',//创建时间
    ispay: false,//是否点击支付
    //点击开启的动画------------------
    isExpress:false,//配送方式的动画
    isShipping:false,//选择配送方式的动画
    cartProduct: {},//单个商品
    index: '',//当前正在操作代付款商品的下标
    //--------------优惠券信息---------------------------
    discountCardList:[],//优惠券列表信息
    cardIdStr:'',//已选择的优惠券id拼接
    couponInfouserId: '',//优惠券id
    couponPrice:0,//优惠金额
    //--------------服务条款----------------------------
    agreeNotes:false,//同意服务条款同意后才能付款
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("order--onLoadJs");
    console.log(options);

    let that = this;
    
    let orderId = options.orderId || that.data.orderId;
   
    //------------判断有无订单，有则为待付款订单----------------------------------
    if (orderId) {
      that.getListByOrderId(orderId);
    }else{
      that.getCartList(orderId);
    }
  },
  onShow: function () {
    rd_session = wx.getStorageSync("rd_session");
    //获取默认地址
    this.getDefaultAddress();
    this.setData({
      isBindPhone: app.data.isBindPhone,
      isAuthorization: app.data.isAuthorization,
      shopName: app.data.shopName
    })
  },
  
  getListByOrderId: function (orderId) {// 根据订单号查订单商品列表

    let that = this;
 
    wx.showLoading({
      title: '加载中',
      mask: true,
      success: function (res) {
        //----------------------根据订单返回商品信息------------------------------
        http.getReq('/weixin/getOrder/ByOrderId', {
          orderId: orderId
        }, function (res) {
          console.log('加载订单商品成功');
          console.log(res);

          //判断订单状态
          let status = res.status;//订单状态
          let address = res.address;//订单地址
          let orderTime = res.orderTime;//创建时间
          let totalCount = res.total;//订单总额
          let buyerMemo = res.buyerMemo;//留言备注

          console.log('订单状态' + status + '---' + address + '---' + orderTime + '---');

          that.setData({
            defaultAddress: address,//默认收货地址
            status: status,//订单状态
            orderTime: orderTime,//创建时间
            totalCount: totalCount,
            hasAddress: true,//有地址
            buyerMemo: buyerMemo,//用户留言
            orderId: orderId,//订单id
            cartProducts: res.data,//代付款商品列表
          })
          wx.hideLoading();
        });
  
      }
    })
  },

  getCartList: function (orderId){//获取待付款商品列表

    let that = this;
    let cartProducts = that.data.cartProducts
    if (cartProducts.length <= 0) {//立即购买的商品
      cartProducts = app.data.cartProducts
    }

    console.log('获取待付款商品列表');
    console.log(cartProducts);
    //---------------------计算商品总额------------------------------------

    let totalCount = 0;//显示合计
    let hasLimit = false;//是否含有限购商品，
    let hasUnvalid = false;//是否有失效商品
    let couponPrice = 0;//优惠券金额

    for (let i = 0; i < cartProducts.length; i++) {

      //优惠金额
      let discountPrice = cartProducts[i].couponPrice || 0;
      couponPrice = couponPrice + discountPrice;

      totalCount = totalCount + parseFloat(cartProducts[i].count * cartProducts[i].price)
      if (cartProducts[i].isLimited == '1') {
        hasLimit = true;//是否含有限购商品， = true;
      }
      if (cartProducts[i].isValid == 0) {
        hasUnvalid = true;//是否含有失效商品， = true;
      }

    }

    //计算优惠减免后的金额
    if (couponPrice > 0 && !orderId) {
      totalCount = parseFloat(totalCount - couponPrice);
    }

    //---------------------获取默认地址------------------------------------
    let address = wx.getStorageSync('address');
    if (address != '') {
      console.log("地址不为空");
      that.setData({
        defaultAddress: address,
        hasAddress: true
      })
    }

    that.setData({
      cartProducts: cartProducts,
      hasLimit: hasLimit,//是否含有限购商品，
      hasUnvalid: hasUnvalid,//是否含有失效商品
      totalCount: totalCount.toFixed(2)
    })

  },

  onReady: function () {
   
  },
 
  //-------登陆动画-------------------
  loginAnimation: function () {
    app.loginAnimation();
    this.setData({
      ispay: false,//不能付款
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin,
    })
  },
  //-------关闭登陆动画--------------
  closeLoginAnimation: function (e) {
    let that = this;
    console.log(e);
    app.closeLoginAnimation(e);
    that.setData({
      isAuthorization: app.data.isAuthorization,
      animationData: app.data.animationData,
      showLogin: app.data.showLogin,
    })
    let wxPay = that.data.wxPay;
    if (that.data.isAuthorization && wxPay) {//查看是否登录、授权
      that.setData({
        ispay: false//按钮状态 可选，（重置可确认支付）
      })
    } else {
      util.showToast('登录失败，无法进行付款', 1000, 'none', function () { });
    }
  },
  //--------------获取.page节点高度，设置#高度mask ----------
  getMaskHeight: function (e) {
    let that = this;
    wx.createSelectorQuery().select('.page').boundingClientRect(function (rect) {
      // 节点的高度
      console.log(rect);
      return rect.height
    }).exec()
  },
  cancelAnimation: function (e) {//取消按钮
    console.log(e);
    let that = this;
    app.cancelAnimation();
    that.setData({
      animationData3: app.data.animationData,
    })

    setTimeout(function(){
      that.setData({
        animationData3: app.data.animationData,
        isshow:false,
        isExpress: false,
        isShipping: false,
      })
    },300)


  },
  //选择配送方式
  chooseShipMethod: function (e) {
    let that = this;
    console.log(e);
    let index = e.currentTarget.dataset.index;
    let cartProducts = that.data.cartProducts;
    let cartProduct = cartProducts[index];
    app.makeAnimation();
    that.setData({
      animationData3: app.data.animationData,
      isshow: true,
      isShipping:true,
      cartProduct: cartProduct,
      index: index,//当前正在操作代付款商品的下标
    })
    setTimeout(function () {
      that.setData({
        animationData3: app.data.animationData,
      })
    }.bind(this), 300)
  },
 
  wxPay: function (e) {//提交订单
    let that = this;
    let isAuthorization = app.data.isAuthorization;
    let orderId = that.data.orderId; //判断订单是否有orderId
    if (isAuthorization){//已登录
      if (!orderId){
        wx.showModal({
          title: '确认支付',
          content: '订单总计' + that.data.totalCount + '元',
          showCancel: true,
          cancelText: '取消',
          confirmText: '确定',
          success: function (res) {
            if (res.confirm) {//提交订单直接支付
              that.setData({
                ispay: false,//按钮状态 可选，（重置可确认支付）
                submitOrderNoPay: false
              })
              app.wxPay(e, that);//提交订单调用支付接口
            } else {//提交订单取消支付，不支付
              that.setData({
                ispay: true,//按钮状态 可选，（重置可确认支付）
                submitOrderNoPay: true
              })
              app.wxPay(e, that);//提交订单调用支付接口
            }
          },
          fail: function (res) { },
          complete: function (res) { },
        })

      }else{
        that.setData({
          ispay: false,//按钮状态 可选，（重置可确认支付）
          submitOrderNoPay: false
        })
        app.wxPay(e, that);//提交订单调用支付接口
      }
    
    }else{//登录
      wx.showModal({
        title: '付款提示',
        content: '您还未登录，请先登录再确认付款',
        showCancel: false,
        success: function (res) {
          //未授权
          that.loginAnimation();
        }
      })
    }
  },

  backToHome: function (e) {//返回到首页
    app.backToHome(this);
  },
  //是否短信通知收货人
  sendMessage: function (e) {
    console.log(e);
    let [that, sendMessage] = [this, e.detail.value];//sendMessage 返回true 或false;
    that.setData({
      sendMessage: sendMessage
    })
  },
  //------------------未开通服务提示----------------------
  unOpen: function () {
    app.unOpen();
  },
  //----数量超出提示--------------------------------------
  hasLimitProTip:function(){
    util.showToast('订单中的商品超出限购数量，请编辑后重试', 1500, 'none', function () { });
  },
  // 设置地址页面
  toSetAddressPage:function(e){
    wx.navigateTo({//跳转设置地址页面
      url: '../setAddress/setAddress',
    })
  },
  //一键复制订单号：
  copyOrderId: function (e) {
    app.copyOrderId(e);
  },
  
  selectShip:function(e){//选择配送方式
    let that = this;
    console.log(e);
    let methodCode = e.currentTarget.dataset.methodcode;//配送id
    let methodName = e.currentTarget.dataset.methodname;//配送名称
    let cartProducts = that.data.cartProducts;
    let index = that.data.index;
    let cartProduct = cartProducts[index];
    cartProduct.shippingMethodCode = methodCode;
    cartProduct.shippingMethodName = methodName;
    for (let i = 0; i < cartProducts.length;i++){
      if (cartProducts[i] == index){
        cartProducts[i] = cartProduct;
      }
    }
    
    that.setData({
      cartProducts: cartProducts,
      // discountCardList: cartProducts.zjCouponInfoVos,//优惠券信息
      cartProduct: cartProduct
    })

  },
  validataShip:function(){
    let cartProducts = this.data.cartProducts;
    let shipAllSelect = true;
    for (let i = 0; i < cartProducts.length; i++) {
      if (cartProducts[i].shippingMethodCode == null) {
        shipAllSelect = false;
      }
    }
    if (!shipAllSelect) {
      util.showToast('请选择配送方式', 1000, 'none', function () { 
        return shipAllSelect;
      });
    }
    return shipAllSelect;
  },
  //计算输入框输入留言字数
  countMemoLength:function(e){
    console.log(e);
    this.setData({
      buyerMemoLength: e.detail.cursor
    })
  },
  //备注留言区失去焦点时
  getBuyerMemo:function(e){
    console.log(e);
    this.setData({
      buyerMemo: e.detail.value
    })
  },
  getFormId: function (e) {
    console.log(e);
    app.getFormId(e);
  },
  //根据商品id 查商品详情
  selectProductById: function (e) {

    console.log('根据商品id 查商品详情参数');
    console.log(e);
    let productId = e.currentTarget.dataset.productid || this.data.productId;
    let that = this;
    console.log(productId);
    this.setData({
      productId: productId,
      pageUrl: '/pages/product/product'
    })
    app.selectProductById(that);

  },
  //选择优惠券
  selectCoupons:function(){

  },
  //获取默认地址
  getDefaultAddress: function () {
    let that = this;
    let defaultAddress = '';
    http.getReq('/weixin/userDeliveredInfo/list', {
      rdSession: rd_session
    }, function (res) {
      let addressList = res.data;
      console.log(res);
      if (res.data.length > 0) {
        for (let i = 0; i < addressList.length; i++) {
          if (addressList[i].isDefault == '1') {
            defaultAddress = addressList[i];
          }
        }
        that.setData({
          hasAddress: true,
          defaultAddress: defaultAddress
        })
      } else {
        that.setData({
          hasAddress: false
        })
      }
    });
  },
  //勾选下单须知
  checkOut:function(){
    let that = this;
    this.setData({
      agreeNotes: !that.data.agreeNotes,//同意购买须知
    })
  }
})